package com.cookbook.interceptor;

import com.cookbook.RequestAuthority;
import com.cookbook.Result;
import com.cookbook.database.model.User;
import com.cookbook.service.UserService;
import com.cookbook.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author 毛川
 */
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object ohandler) throws Exception {
        logger.debug("authority", "begin validate authority.");

        if (!(ohandler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handler = (HandlerMethod) ohandler;
        RequestAuthority authority = handler.getMethodAnnotation(RequestAuthority.class);

        if (null == authority) {
            //没有声明权限,放行
            return true;
        }

        logger.debug("authority", authority.toString());

        String token = request.getHeader("auth_token");
        if (StringUtils.isEmpty(token)) {
            response.setContentType("application/x-json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(Result.format(Result.NO_PERMISSION, "没有权限"));
            return false;
        }

        logger.debug("authority", token);

        Claims claims = JWTUtils.parseToken(token);

        if (JWTUtils.isExpired(claims)) {
            response.setContentType("application/x-json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(Result.format(Result.AUTHORITY_EXPIRED, "授权过期"));
            return false;
        }

        logger.debug("authority", "try find user.");

        String username = JWTUtils.getUsername(claims);
        User user;

        try {
            user = service.findUserByUsername(username);
            if (user == null) {
                response.setContentType("application/x-json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(Result.format(Result.PERMISSION_ERROR, "权限错误"));
                return false;
            }
        } catch (Exception e) {
            response.setContentType("application/x-json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(Result.format(Result.INTERNAL_ERROR, "内部错误"));
            return false;
        }

        HttpSession session = request.getSession();
        session.setAttribute("user", user);

        return true;
    }

}
